#include "app_mqtt.h"
#include "log/log.h"
#include <MQTTClient.h>

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;


static int (*recv_callback)(char *,int);
//发送消息的回调函数
static void delivered(void *contxt,MQTTClient_deliveryToken dt){
    log_debug("delivered dt:%d",dt);
}
//收到消息的回调函数
static int msgarrv(void *context,char *topicName,int topicLen,MQTTClient_message *message){
    int reslut = 0;
    if(recv_callback){
        reslut = recv_callback((char *)message->payload,message->payloadlen)=0?1:0;
    }
    //释放消息资源
    MQTT_Client_freeMessage(&message);
    MQTT_Client_free(topicName);
    //返回消息处理结果
    return reslut;

}
/**
 * @brief 连接断开的回调函数
 * 
 */
static void connlost(void *context,char *cause){
    log_error("Connection lost cause: %s\n",cause);
}

/**
 * 初始化mqtt客户端
 */
int app_mqtt_init(void){
    int result;
    //创建客户端
    if (result=MQTTClient_create(&client, MQTT_SERVER, MQTT_CLIENT_ID, MQTTCLIENT_PERSISTENCE_NONE, NULL))  
    {
        log_error("MQTTClient_create error:%d",result);
        return -1;
    }
    
    //注册回调函数
    MQTTClient_setCallbacks(client, NULL, NULL, app_mqtt_recv_callback, NULL);
    //链接服务器
    if((result=MQTTClient_connect(client, &conn_opts))){
        log_error("MQTTClient_connect error:%d",result);
        MQTTClient_destroy(&client);
        return -1;
    }
    //订阅主题
    if((result=MQTTClient_subscribe(client, MQTT_TOPIC, MQTT_QOS))){
        log_error("MQTTClient_subscribe error:%d",result);
        app_mqtt_close();
        return -1;
    }
}
/**
 * 发送消息
 */
int app_mqtt_send(char *data,int len){
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = MQTT_QOS;

    if(MQTTClient_publish(client, MQTT_TOPIC, &pubmsg))
}
/**
 * 注册接收mqtt消息回调函数
 */
void app_mqtt_registRecvCallback(int (*callback)(char *,int )){

}
/**
 * 关闭
 */
void app_mqtt_close(void){
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}